﻿using FreesenseSubAIS.InspProcess;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FreesenseSubAIS
{
    /// <summary>
    /// 系统功能类
    /// </summary>
    public class SystemCommon
    {

        private static List<Tuple<string, List<string>, bool>> mFunctionList;

        public SystemCommon()
        {

        }



        public static List<Tuple<float, int>> ListVCOM { get; set; }//电压值表




        /// <summary>
        /// 加载执行文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="rowType"></param>
        /// <returns></returns>
        /// 
        public static List<InspRow> LoadConfig(string filePath, InspRowType rowType)
        {


            //var fullPath2 = Path.Combine(Device.ProjectPath, Device.Parameter.DefaultProductId, "list_vcom.xls");

            try
            {
                if (File.Exists(filePath))
                {
                    HSSFWorkbook wk = null;
                    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        wk = new HSSFWorkbook(fs);
                    }

                    ISheet sheet = wk.GetSheetAt(0);//获取工作表sheet1
                    List<InspRow> rows = new List<InspRow>(sheet.LastRowNum);
                    for (int i = 0; i < sheet.LastRowNum; i++)
                    {
                        rows.Add(new InspRow());
                    }
                    List<ICell> head = sheet.GetRow(0).Cells;//表头
                    PropertyInfo[] pIs = typeof(InspRow).GetProperties();
                    Type t = null;
                    //if (rowType == InspRowType.AISRow)
                    //{
                    //    t = typeof(AISInputParameter);
                    //    mFunctionList = GetAisFunctionList();
                    //}

                    PropertyInfo[] inputProp = t.GetProperties();
                    for (int i = 0; i < pIs.Length; i++)
                    {
                        PropertyInfo cp = pIs[i];



                        if (cp.PropertyType == typeof(int))
                        {
                            for (int j = 0; j < sheet.LastRowNum; j++)//遍历除列头外所有行
                            {
                                var temp = sheet.GetRow(j + 1).GetCell(i);
                                cp.SetValue(rows[j], int.Parse(temp != null ? temp.ToString() : ""), null);

                            }
                        }



                        else if (cp.PropertyType == typeof(BaseInputParameter))
                        {
                            if (head[1].ToString() == "Function_Name")
                                for (int j = 0; j < sheet.LastRowNum; j++)//遍历除列头外所有行
                                {
                                    var temp = sheet.GetRow(j + 1).GetCell(1);
                                    var temp2 = sheet.GetRow(j + 1).GetCell(i);
                                    cp.SetValue(rows[j], AnalysisParams(temp != null ? temp.ToString() : "", temp2 != null ? temp2.ToString() : "", inputProp, rowType), null);
                                }

                        }

                        else if (cp.PropertyType == typeof(char))
                        {
                            for (int j = 0; j < sheet.LastRowNum; j++)//遍历除列头外所有行
                            {
                                var temp = sheet.GetRow(j + 1).GetCell(i);
                                cp.SetValue(rows[j], Convert.ToChar(temp != null ? temp.ToString() : ""), null);

                            }
                        }


                        else
                        {
                            for (int j = 0; j < sheet.LastRowNum; j++)//遍历除列头外所有行
                            {
                                var temp = sheet.GetRow(j + 1).GetCell(i);
                                cp.SetValue(rows[j], temp != null ? temp.ToString() : "", null);

                            }
                        }
                    }
                    return rows.ToList().FindAll(data => data.On_Fire == 'Y');
                }
                return null;


            }
            catch (Exception ex)
            {
                throw new Exception("API脚本配置错误："+ex.Message);
            }

        }
        public static void GetVCOMList(string filePath)
        {
            if (File.Exists(filePath))
            {
                //2.载入vcom调节文件
                HSSFWorkbook wk = null;
                using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    wk = new HSSFWorkbook(fs);
                }

                ISheet sheet = wk.GetSheetAt(0);//获取工作表sheet1
                List<ICell> head = sheet.GetRow(0).Cells;//表头
                ListVCOM = new List<Tuple<float, int>>();

                for (int j = 0; j < sheet.LastRowNum; j++)//遍历除列头外所有行
                {
                    float vcom = 0;
                    int channel = 0;
                    var vTemp = sheet.GetRow(j + 1).GetCell(0);
                    var cTemp = sheet.GetRow(j + 1).GetCell(1);
                    float.TryParse(vTemp != null ? vTemp.ToString() : "", out vcom);
                    int.TryParse(cTemp != null ? cTemp.ToString() : "", out channel);
                    ListVCOM.Add(new Tuple<float, int>(vcom, channel));
                }



            }
        }




        private static BaseInputParameter AnalysisParams(string functionName, string inputParams, PropertyInfo[] inputProp, InspRowType rowType)
        {
            try
            {


                string[] ps = inputParams.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                var count = ps.Count();
                if (count == 0 && !string.IsNullOrEmpty(inputParams)) return null;   //不符合参数@前缀，返回null

                BaseInputParameter inputPara = null;
                //if (rowType == InspRowType.AISRow)
                //{
                //    inputPara = new AISInputParameter();
                //}
                var fDef = (from data in mFunctionList where data.Item1 == functionName select data).First();

                foreach (var p in inputProp)
                {
                    var index = -1;
                    for (int i = 0; i < count; i++)
                    {
                        if (p.Name == fDef.Item2[i])
                        {
                            index = i;
                            break;
                        }
                    }
                    if (index > -1)
                    {
                        if (p.PropertyType == typeof(String))
                        {
                            p.SetValue(inputPara, ps[index], null);
                        }
                        else if (p.PropertyType == typeof(char))
                        {
                            p.SetValue(inputPara, Convert.ToChar(ps[index]), null);
                        }
                        else if (p.PropertyType == typeof(Single))
                        {
                            p.SetValue(inputPara, Single.Parse(ps[index]), null);
                        }
                        else if (p.PropertyType == typeof(int))
                        {
                            p.SetValue(inputPara, int.Parse(ps[index]), null);
                        }

                    }
                }
                return inputPara;
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }





        /// <summary>
        /// 
        /// </summary>
        /// <returns>Turple Item1:FunctionName Item2:输入的各个参数名称 Item3:结果是否显示到界面</returns>
        private static List<Tuple<string, List<string>, bool>> GetAisFunctionList()
        {
            var functionList = new List<Tuple<string, List<string>, bool>>()
            {
                 new Tuple<string, List<string>, bool>("ETS_SendComand",
                    new List<string>() { "Command","IntervalDelayTime" }, false),
                new Tuple<string, List<string>, bool>("ETS_ChangeColor",
                    new List<string>() { "ColorFileName","IntervalDelayTime" }, false),
                new Tuple<string, List<string>, bool>("CA_Extend_VCOMAdjust",
                    new List<string>() { "ColorFileName","DisplayCode","IntervalDelayTime"}, false),
                new Tuple<string, List<string>, bool>("CA_Return_VCOMAdjust",
                    new List<string>() { "ColorFileName","MinValue","MaxValue" }, false),
                new Tuple<string, List<string>, bool>("OneShot",
                    new List<string>() {"IntervalDelayTime" }, false),
                      new Tuple<string, List<string>, bool>("OneShotForUniformity",
                    new List<string>() {"IntervalDelayTime" }, false),
                         new Tuple<string, List<string>, bool>("OneShotForFramCorrect",
                    new List<string>() {"IntervalDelayTime" }, false),
                       new Tuple<string, List<string>, bool>("OneShotForRGBCorrect",
                    new List<string>() {"IntervalDelayTime" }, false),
                new Tuple<string, List<string>, bool>("SYS_DL_CONTINUE",
                    new List<string>() { "Msg" }, false)
            };
            return functionList;
        }

        public static void ReNameConfigFile(string newName, string filePath)
        {
            if (File.Exists(filePath))
            {
                FileInfo fi = new FileInfo(filePath);

                fi.MoveTo(Path.Combine(fi.DirectoryName, newName));
            }
        }
        public static void CopyConfigFile(string newfilePath, string oldfilePath)
        {
            if (File.Exists(oldfilePath))
            {
                FileInfo fi = new FileInfo(oldfilePath);

                fi.CopyTo(newfilePath);

            }
        }

        public static void SaveLogFile(string content, string fullName)
        {
            FileInfo fi = new FileInfo(fullName);
            if (!fi.Directory.Exists)
            {
                throw new Exception("错误消息：网络硬盘找不到！\r\n解决方法:\r\n1.请检查config.csv文件中远程日志路径是否设置正确。");
            }
            FileStream fs = new FileStream(fullName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            sw.Write(content);
            sw.Close();
        }


    }
}
